﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DDay.iCal;
using DDay.iCal.Components;
using DDay.iCal.Serialization;
using Telerik.Events;

namespace SelArom.Net.Sitefinity.HttpHandlers
{
	/// <summary>
	/// HttpHandler for creating iCal (Outlook) reminders
	/// </summary>
	public class EventReminder : IHttpHandler
	{
		public void ProcessRequest(HttpContext context)
		{
			// make sure ID was passed and is valid
			if (string.IsNullOrEmpty(context.Request.QueryString["id"]))
				context.Response.Redirect("~/404.aspx", true);

			Guid id;
			try
			{
				id = new Guid(context.Request.QueryString["id"]);
			}
			catch
			{
				id = Guid.Empty;
			}

			if (id == Guid.Empty)
				context.Response.Redirect("~/404.aspx", true);

			var mgr = new EventsManager(EventsManager.DefaultContentProvider);
			var ev = mgr.GetEvent(id);
			if (ev == null)
			{
				context.Response.Redirect("~/404.aspx", true);
				return;
			}

			var cal = new iCalendar { Version = "1.0" };
			var appt = cal.Create<Event>();
			appt.Start = ev.Start.ToUniversalTime();
			appt.End = ev.End.ToUniversalTime();

			// strip out all html tags
			var reg = new Regex("<(.|\n)+?>");
			var description = reg.Replace(ev.ContentItem.Content.ToString(), "");
			var location = ev.ContentItem.GetMetaData("Location");
			location = location == null ? ev.ContentItem.GetMetaData("Street") : string.Concat(location, " (", ev.ContentItem.GetMetaData("Street"), ")");

			appt.Location = location.ToString();
			appt.Summary = ev.EventTitle;
			appt.Description = description;

			var ser = new iCalendarSerializer(cal);
			context.Response.Clear();
			context.Response.ContentType = "text/calendar";
			context.Response.AddHeader("content-disposition", "attachment; filename=EventReminder.ics");
			context.Response.Write(ser.SerializeToString());
			context.Response.End();
		}

		public bool IsReusable
		{
			get { return false; }
		}
	}
}
